import Store from 'electron-store';
import * as crypto from 'crypto';

export interface CloudConfig {
  provider: 'tencent' | 'aliyun' | 'bytedance' | 'aws' | 'huawei';
  accessKeyId: string;
  secretAccessKey: string;
  region: string;
  bucket: string;
  endpoint?: string;
  accountName?: string; // 自定义账号名称
  accountId?: string;   // 账号唯一标识
}

export interface CloudAccountConfig {
  id: string;
  name: string;
  config: CloudConfig;
  isDefault?: boolean;
}

export class ConfigManager {
  private store: Store;
  private encryptionKey: string;

  constructor() {
    this.store = new Store({
      name: 'cloud-uploader-config',
      encryptionKey: 'cloud-uploader-secret-key'
    });
    this.encryptionKey = 'cloud-uploader-encryption-key';
  }

  /**
   * 保存云服务配置（兼容旧版本）
   */
  async saveConfig(config: CloudConfig): Promise<boolean> {
    const accountId = config.accountId || 'default';
    const accountName = config.accountName || '默认账号';
    return this.saveAccountConfig(config.provider, accountId, accountName, config);
  }

  /**
   * 保存账号配置
   */
  async saveAccountConfig(provider: string, accountId: string, accountName: string, config: CloudConfig): Promise<boolean> {
    try {
      // 加密敏感信息
      const encryptedConfig = {
        ...config,
        accessKeyId: this.encrypt(config.accessKeyId),
        secretAccessKey: this.encrypt(config.secretAccessKey),
        accountId,
        accountName
      };

      // 获取现有账号列表
      const accounts = this.getProviderAccounts(provider);
      const existingIndex = accounts.findIndex(acc => acc.id === accountId);
      
      const accountConfig: CloudAccountConfig = {
        id: accountId,
        name: accountName,
        config: encryptedConfig,
        isDefault: accounts.length === 0 // 第一个账号设为默认
      };

      if (existingIndex >= 0) {
        accounts[existingIndex] = accountConfig;
      } else {
        accounts.push(accountConfig);
      }

      this.store.set(`accounts.${provider}`, accounts);
      return true;
    } catch (error) {
      console.error('保存配置失败:', error);
      return false;
    }
  }

  /**
   * 获取云服务配置（兼容旧版本，返回默认账号）
   */
  async getConfig(provider: string): Promise<CloudConfig | null> {
    const accounts = this.getProviderAccounts(provider);
    if (accounts.length === 0) {
      // 尝试从旧版本配置中获取
      return this.getLegacyConfig(provider);
    }
    
    const defaultAccount = accounts.find(acc => acc.isDefault) || accounts[0];
    return this.getAccountConfig(provider, defaultAccount.id);
  }

  /**
   * 获取指定账号的配置
   */
  async getAccountConfig(provider: string, accountId: string): Promise<CloudConfig | null> {
    try {
      const accounts = this.getProviderAccounts(provider);
      const account = accounts.find(acc => acc.id === accountId);
      
      if (!account) {
        return null;
      }

      const encryptedConfig = account.config;
      // 解密敏感信息
      return {
        ...encryptedConfig,
        accessKeyId: this.decrypt(encryptedConfig.accessKeyId),
        secretAccessKey: this.decrypt(encryptedConfig.secretAccessKey)
      };
    } catch (error) {
      console.error('获取配置失败:', error);
      return null;
    }
  }

  /**
   * 获取旧版本配置（向后兼容）
   */
  private async getLegacyConfig(provider: string): Promise<CloudConfig | null> {
    try {
      const encryptedConfig = this.store.get(`config.${provider}`) as CloudConfig;
      if (!encryptedConfig) {
        return null;
      }

      // 解密敏感信息
      return {
        ...encryptedConfig,
        accessKeyId: this.decrypt(encryptedConfig.accessKeyId),
        secretAccessKey: this.decrypt(encryptedConfig.secretAccessKey)
      };
    } catch (error) {
      console.error('获取旧版本配置失败:', error);
      return null;
    }
  }

  /**
   * 获取所有已配置的云服务提供商
   */
  getConfiguredProviders(): string[] {
    const accounts = this.store.get('accounts', {}) as Record<string, any>;
    const legacyConfig = this.store.get('config', {}) as Record<string, any>;
    
    const providers = new Set([...Object.keys(accounts), ...Object.keys(legacyConfig)]);
    return Array.from(providers);
  }

  /**
   * 获取指定提供商的所有账号
   */
  getProviderAccounts(provider: string): CloudAccountConfig[] {
    return this.store.get(`accounts.${provider}`, []) as CloudAccountConfig[];
  }

  /**
   * 获取指定提供商的账号列表（仅包含基本信息）
   */
  getProviderAccountList(provider: string): { id: string; name: string; isDefault: boolean }[] {
    const accounts = this.getProviderAccounts(provider);
    return accounts.map(acc => ({
      id: acc.id,
      name: acc.name,
      isDefault: acc.isDefault || false
    }));
  }

  /**
   * 设置默认账号
   */
  setDefaultAccount(provider: string, accountId: string): boolean {
    try {
      const accounts = this.getProviderAccounts(provider);
      
      // 清除所有默认标记
      accounts.forEach(acc => acc.isDefault = false);
      
      // 设置新的默认账号
      const targetAccount = accounts.find(acc => acc.id === accountId);
      if (targetAccount) {
        targetAccount.isDefault = true;
        this.store.set(`accounts.${provider}`, accounts);
        return true;
      }
      
      return false;
    } catch (error) {
      console.error('设置默认账号失败:', error);
      return false;
    }
  }

  /**
   * 删除配置（兼容旧版本，删除所有账号）
   */
  deleteConfig(provider: string): boolean {
    try {
      this.store.delete(`config.${provider}`);
      this.store.delete(`accounts.${provider}`);
      return true;
    } catch (error) {
      console.error('删除配置失败:', error);
      return false;
    }
  }

  /**
   * 删除指定账号
   */
  deleteAccount(provider: string, accountId: string): boolean {
    try {
      const accounts = this.getProviderAccounts(provider);
      const filteredAccounts = accounts.filter(acc => acc.id !== accountId);
      
      // 如果删除的是默认账号，设置第一个账号为默认
      const deletedAccount = accounts.find(acc => acc.id === accountId);
      if (deletedAccount?.isDefault && filteredAccounts.length > 0) {
        filteredAccounts[0].isDefault = true;
      }
      
      this.store.set(`accounts.${provider}`, filteredAccounts);
      return true;
    } catch (error) {
      console.error('删除账号失败:', error);
      return false;
    }
  }

  /**
   * 加密字符串
   */
  private encrypt(text: string): string {
    const cipher = crypto.createCipher('aes-256-cbc', this.encryptionKey);
    let encrypted = cipher.update(text, 'utf8', 'hex');
    encrypted += cipher.final('hex');
    return encrypted;
  }

  /**
   * 解密字符串
   */
  private decrypt(encryptedText: string): string {
    const decipher = crypto.createDecipher('aes-256-cbc', this.encryptionKey);
    let decrypted = decipher.update(encryptedText, 'hex', 'utf8');
    decrypted += decipher.final('utf8');
    return decrypted;
  }

  /**
   * 验证配置是否有效
   */
  validateConfig(config: CloudConfig): boolean {
    const requiredFields = ['provider', 'accessKeyId', 'secretAccessKey', 'region', 'bucket'];
    return requiredFields.every(field => config[field as keyof CloudConfig]);
  }

  /**
   * 保存远程目录历史记录
   */
  saveRemotePathHistory(remotePath: string): void {
    try {
      const history = this.getRemotePathHistory();
      
      // 移除重复项
      const filteredHistory = history.filter(path => path !== remotePath);
      
      // 添加到开头
      filteredHistory.unshift(remotePath);
      
      // 限制历史记录数量为10条
      const limitedHistory = filteredHistory.slice(0, 10);
      
      this.store.set('remotePathHistory', limitedHistory);
    } catch (error) {
      console.error('保存远程目录历史记录失败:', error);
    }
  }

  /**
   * 获取远程目录历史记录
   */
  getRemotePathHistory(): string[] {
    try {
      return this.store.get('remotePathHistory', []) as string[];
    } catch (error) {
      console.error('获取远程目录历史记录失败:', error);
      return [];
    }
  }

  /**
   * 获取最后一次使用的远程目录
   */
  getLastRemotePath(): string {
    const history = this.getRemotePathHistory();
    return history.length > 0 ? history[0] : '/';
  }

  /**
   * 保存本地目录历史记录
   */
  saveLocalPathHistory(localPath: string): void {
    try {
      const history = this.getLocalPathHistory();
      
      // 移除重复项
      const filteredHistory = history.filter(path => path !== localPath);
      
      // 添加到开头
      filteredHistory.unshift(localPath);
      
      // 限制历史记录数量为10条
      const limitedHistory = filteredHistory.slice(0, 10);
      
      this.store.set('localPathHistory', limitedHistory);
    } catch (error) {
      console.error('保存本地目录历史记录失败:', error);
    }
  }

  /**
   * 获取本地目录历史记录
   */
  getLocalPathHistory(): string[] {
    try {
      return this.store.get('localPathHistory', []) as string[];
    } catch (error) {
      console.error('获取本地目录历史记录失败:', error);
      return [];
    }
  }

  /**
   * 获取最后一次使用的本地目录
   */
  getLastLocalPath(): string {
    const history = this.getLocalPathHistory();
    return history.length > 0 ? history[0] : '';
  }
}